package com.ontology.util.parser.file.impl;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

import com.ontology.util.model.OColumn;
import com.ontology.util.model.ORow;
import com.ontology.util.model.OTable;
import com.ontology.util.model.impl.OntologyTable;
import com.ontology.util.parser.OLineParser;
import com.ontology.util.parser.content.ExcelRowParser;
public class ExcelFileParser extends AbstractFileParser<OTable> {
	private OLineParser<Row>	lineParser	= new ExcelRowParser();
	public List<OTable> parse(String pathname) throws InvalidFormatException,
	IOException {
		return parse(new File(pathname));
	}
	public List<OTable> parse(File file) throws InvalidFormatException,
	IOException {
		List<OTable> tables = new ArrayList<OTable>();
		InputStream inp = new FileInputStream(file);
		Workbook wb = WorkbookFactory.create(inp);
		int numOfSheets = wb.getNumberOfSheets();
		for (int sheetIndex = 0; sheetIndex < numOfSheets; sheetIndex++) {
			OTable oTable = parseSheet(wb.getSheetAt(sheetIndex));
			if (oTable != null) {
				tables.add(oTable);
			}
		}
		return tables;
	}
	public OTable parseSheet(Sheet sheet) {
		if (sheet == null) {
			return null;
		}
		List<OColumn> columns = lineParser.parseHeaderLine(sheet.getRow(0));
		if (columns.size() == 0) {
			return null;
		}
		OntologyTable oTable = new OntologyTable();
		oTable.setRows(new ArrayList<ORow>());
		oTable.setColumns(columns);
		System.out.println(sheet.getLastRowNum()  + " Physical " + sheet.getPhysicalNumberOfRows());
		int rowEnd = Math.max(1, sheet.getPhysicalNumberOfRows());
		for (int rowIndex = 1; rowIndex < rowEnd; rowIndex++) {
			ORow row = lineParser.parseLine(sheet.getRow(0), columns);
			if (row == null) {
				break;
			}
			oTable.getRows().add(row);
		}
		return oTable;
	}
	public Set<String> getEligibleBlankValues() {
		// TODO Auto-generated method stub
		return null;
	}
}
